package cn.edu.buu.hospital.web;

import cn.edu.buu.hospital.entity.Hospital;
import cn.edu.buu.hospital.service.HospitalService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletRequest;

import java.time.LocalDateTime;

@Controller
@RequestMapping("/hospital")
public class HospitalController {

    @Autowired
    private HospitalService hospitalService;

    // 跳转到新增医院页面
    @GetMapping("/toAdd")
    public String toAdd() {
        return "backend/hospital/add";
    }

    // 新增医院
    @PostMapping("/add")
    @Transactional
    public String add(@RequestParam("hospitalname") String hospitalname,
                     @RequestParam("address") String address,
                     @RequestParam("hphone") String hphone,
                     Model model) {
        try {
            // 创建医院对象并设置属性
            Hospital hospital = new Hospital();
            hospital.setHospitalname(hospitalname);
            hospital.setAddress(address);
            hospital.setHphone(hphone);
            
            hospitalService.add(hospital);
            return "redirect:find";
        } catch (Exception e) {
            // 保存错误信息到session，因为重定向会丢失model
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            request.getSession().setAttribute("error", "新增失败: " + e.getMessage());
            
            // 创建临时对象保存用户输入
            Hospital temp = new Hospital();
            temp.setHospitalname(hospitalname);
            temp.setAddress(address);
            temp.setHphone(hphone);
            request.getSession().setAttribute("addHospital", temp);
            
            return "redirect:toAdd";
        }
    }

    // 查询医院列表
    @RequestMapping(value = "/find", method = {RequestMethod.GET, RequestMethod.POST})
    public String find(Model model,
                      @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                      Hospital condition) {
        int pageSize = 5;
        PageInfo<Hospital> pageInfo = hospitalService.find(pageNum, pageSize, condition);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("condition", condition);
        return "backend/hospital/list";
    }

    // 跳转到编辑页面
    @GetMapping("/toEdit")
    public String toEdit(@RequestParam("hospitalId") Long hospitalId, Model model) {
        // 根据ID查询医院信息
        Hospital hospital = hospitalService.findById(hospitalId);
        if (hospital == null) {
            hospital = new Hospital();
            hospital.setHospitalid(hospitalId);
        }
        model.addAttribute("hospital", hospital);
        return "backend/hospital/edit";
    }

    // 根据ID查询医院（用于编辑）
    @GetMapping("/findById")
    public String findById(@RequestParam("hospitalId") Long hospitalId, Model model) {
        // 根据ID查询医院信息
        Hospital hospital = hospitalService.findById(hospitalId);
        if (hospital == null) {
            hospital = new Hospital();
            hospital.setHospitalid(hospitalId);
        }
        model.addAttribute("hospital", hospital);
        return "backend/hospital/edit";
    }

    // 修改医院信息
    @PostMapping("/modify")
    @Transactional
    public String modify(@RequestParam("hospitalid") Long hospitalid,
                        @RequestParam("hospitalname") String hospitalname,
                        @RequestParam("address") String address,
                        @RequestParam("hphone") String hphone,
                        Model model) {
        try {
            // 创建医院对象并设置属性
            Hospital hospital = new Hospital();
            hospital.setHospitalid(hospitalid);
            hospital.setHospitalname(hospitalname);
            hospital.setAddress(address);
            hospital.setHphone(hphone);
            
            hospitalService.modify(hospital);
            return "redirect:find";
        } catch (Exception e) {
            // 保存错误信息和表单数据到session，因为重定向会丢失model
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            request.getSession().setAttribute("error", "修改失败: " + e.getMessage());
            
            // 创建临时对象保存用户输入
            Hospital temp = new Hospital();
            temp.setHospitalid(hospitalid);
            temp.setHospitalname(hospitalname);
            temp.setAddress(address);
            temp.setHphone(hphone);
            request.getSession().setAttribute("editHospital", temp);
            
            return "redirect:toEdit?hospitalId=" + hospitalid;
        }
    }

    // 删除医院
    @GetMapping("/removeById")
    @Transactional
    public String removeById(@RequestParam("hospitalId") Long hospitalId) {
        try {
            hospitalService.removeById(hospitalId);
            return "redirect:find";
        } catch (Exception e) {
            // 保存错误信息到session
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            request.getSession().setAttribute("error", "删除失败: " + e.getMessage());
            return "redirect:find";
        }
    }
}